<template>
    <div>
        <el-form-item label="onChange">
            <div style="display: flex;justify-content: flex-end">
                <el-button @click="openDialogCode"><img src="@/assets/bianxie.png"
                                                        style="width: 10px;height: 10px;margin-right: 5px"/>编写代码
                </el-button>
            </div>
        </el-form-item>
        <el-dialog
                v-if="dialogVisible"
                title="组件事件处理"
                :visible.sync="dialogVisible"
                width="50%"
                class="small-padding-dialog"
                :append-to-body="true"
        >
            <el-alert type="info" :closable="false" :title="eventHeader"></el-alert>
            <codeEditor :mode="'javascript'" :readonly="false" v-model="eventHandlerCode"
                        ref="ecEditor"></codeEditor>
            <el-alert type="info" :closable="false" title="}"></el-alert>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">
                    取消</el-button>
                <el-button type="primary" @click="saveEventHandler">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import codeEditor from "@/components/code-editor/index.vue";

export default {
    name: "onChangeValue-editor",
    components: {
        codeEditor
    },
    props: {
        self0ptions: {
            type: Object,
        }
    },
    data() {
        return {
            eventHeader: '',
            eventHandlerCode:'',
            dialogVisible: false
        }
    },
    methods: {
        openDialogCode() {
            const eventName = 'onChange'
            this.eventHeader = `${this.self0ptions.options.name}.${eventName}() {`
            //恢复默认
            this.eventHandlerCode =  this.self0ptions.options.onChangeValue || ''
            this.dialogVisible = true
        },
        saveEventHandler() {
            const codeHints = this.$refs.ecEditor.getEditorAnnotations()
            let syntaxErrorFlag = false
            if (!!codeHints && (codeHints.length > 0)) {
                codeHints.forEach((chItem) => {
                    if (chItem.type === 'error') {
                        syntaxErrorFlag = true
                    }
                })

                if (syntaxErrorFlag) {
                    this.$message.error('JS代码存在语法错误，请仔细检查！')
                    return
                }
            }

            this.self0ptions.options.onChangeValue = this.eventHandlerCode
            this.dialogVisible = false
        },
    }
}
</script>

<style scoped lang="scss">
.small-padding-dialog {
    ::v-deep .el-dialog__body {
        padding: 6px 15px 12px 15px;
    }
}
</style>